
import { getMenuTree, getLoginUser } from '@/api/common'
const modules = import.meta.glob(['../views/**/**/**.vue'])
import { userStore } from '../store/index.js'
// 生成动态路由
export const generateRoutes = () => {
  const store = userStore()
  return new Promise((resolve, reject) => {
    getMenuTree({})
      .then((res) => {
        // 菜单
        const result = res.data || []
        const dynamicMenus = transformMenus(result)
        store.setProjectMenus(dynamicMenus) // pinia
        // 路由
        const dynamicRoutes = transformRoutes(result)
        resolve(dynamicRoutes)
      })
      .catch((error) => {
        reject(error)
      })
    // getLoginUser({})
    //   .then((res) => {
    //     // 菜单
    //     const result = res.data.userMenus || []
    //     const dynamicMenus = transformMenus(result)
    //     store.setProjectMenus(JSON.stringify(dynamicMenus)) // pinia
    //     // 路由
    //     const dynamicRoutes = transformRoutes(result)
    //     resolve(dynamicRoutes)
    //   })
    //   .catch((error) => {
    //     reject(error)
    //   })

  })
}

// 转换为路由数据为组件
const transformRoutes = (result) => {
  const routes = JSON.parse(JSON.stringify(result))
  const asyncRoutes = []

  routes.forEach((route) => {
    const tmpRoute = { ...route }
    let newRoute = {
      name: tmpRoute.routeName,
      path: tmpRoute.routePath,
      meta: { icon: tmpRoute.icon, status: tmpRoute.status, title: tmpRoute.name || '未配置' },
      children: []
    }
    // 其他菜单，根据组件路径动态加载组件
    if ([1].includes(tmpRoute.type)) {
      // 目录
      newRoute.redirect = tmpRoute.redirect
    } else {
      // 菜单
      const component = modules[`../views/${tmpRoute.component}.vue`]
      if (component) {
        newRoute.component = component
      } else {
        newRoute.component = modules[`../views/exception/404.vue`]
      }
    }

    if (tmpRoute.children) {
      newRoute.children = transformRoutes(tmpRoute.children)
    }

    asyncRoutes.push(newRoute)
  })
  return asyncRoutes
}

// 转换为菜单数据为组件
const transformMenus = (result) => {
  const routes = JSON.parse(JSON.stringify(result))
  const asyncMenus = []
  routes.forEach((route) => {
    const tmpRoute = { ...route }
    // 其他菜单，根据组件路径动态加载组件
    if (tmpRoute.children) {
      tmpRoute.children = transformMenus(tmpRoute.children)
    }
    if ([1].includes(tmpRoute.status)) {
      // 非禁用路由
      asyncMenus.push(tmpRoute)
    }
  })
  return asyncMenus
}
